Security News
vlt Debuts New JavaScript Package Manager and Serverless Registry at NodeConf EU
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
The execa npm package is a process execution tool that simplifies working with child processes in Node.js. It provides a better user experience than the default child_process module by offering a promise-based API, improved Windows support, and additional convenience options.
Executing a shell command
This feature allows you to execute a shell command and obtain the result. The example shows how to execute the 'echo' command and print 'unicorns' to the console.
const execa = require('execa');
(async () => {
const { stdout } = await execa('echo', ['unicorns']);
console.log(stdout);
})();
Running a command synchronously
This feature is used to execute a command synchronously, blocking the event loop until the process has finished. The example synchronously executes the 'echo' command and logs the result.
const execa = require('execa');
const { stdout } = execa.sync('echo', ['unicorns']);
console.log(stdout);
Handling errors
This feature demonstrates error handling when a command fails to execute. The example attempts to run a non-existent command and catches the error.
const execa = require('execa');
(async () => {
try {
const { stdout } = await execa('wrong-command');
console.log(stdout);
} catch (error) {
console.error('Error occurred:', error);
}
})();
Streaming output
This feature allows you to stream the output of a command directly to the console or another stream. The example streams the output of the 'echo' command to the process's stdout.
const execa = require('execa');
const subprocess = execa('echo', ['unicorns']);
subprocess.stdout.pipe(process.stdout);
ShellJS is a portable Unix shell commands implementation for Node.js. It offers a higher-level API for executing commands but does not support returning promises natively.
Cross-spawn is a cross-platform solution for spawning child processes. It aims to solve compatibility issues on Windows but does not provide a promise-based API.
A better
child_process
stdout.trim()
.$ npm install --save execa
const execa = require('execa');
execa('echo', ['unicorns']).then(result => {
console.log(result.stdout);
//=> 'unicorns'
});
// pipe the child process stdout to the current stdout
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
execa.shell('echo unicorns').then(result => {
console.log(result.stdout);
//=> 'unicorns'
});
// example of catching an error
execa.shell('exit 3').catch(error => {
console.log(error);
/*
{
message: 'Command failed: /bin/sh -c exit 3'
killed: false,
code: 3,
signal: null,
cmd: '/bin/sh -c exit 3',
stdout: '',
stderr: '',
timedOut: false
}
*/
});
// example of catching an error with a sync method
try {
execa.shellSync('exit 3');
} catch (err) {
console.log(err);
/*
{
message: 'Command failed: /bin/sh -c exit 3'
code: 3,
signal: null,
cmd: '/bin/sh -c exit 3',
stdout: '',
stderr: '',
timedOut: false
}
*/
}
Execute a file.
Think of this as a mix of child_process.execFile
and child_process.spawn
.
Returns a child_process
instance, which is enhanced to also be a Promise
for a result Object
with stdout
and stderr
properties.
Same as execa()
, but returns only stdout
.
Same as execa()
, but returns only stderr
.
Execute a command through the system shell. Prefer execa()
whenever possible, as it's both faster and safer.
Returns a child_process
instance.
The child_process
instance is enhanced to also be promise for a result object with stdout
and stderr
properties.
Execute a file synchronously.
Returns the same result object as child_process.spawnSync
.
This method throws an Error
if the command fails.
Execute a command synchronously through the system shell.
Returns the same result object as child_process.spawnSync
.
Type: Object
Type: string
Default: process.cwd()
Current working directory of the child process.
Type: Object
Default: process.env
Environment key-value pairs. Extends automatically from process.env
. Set extendEnv
to false
if you don't want this.
Type: boolean
Default: true
Set to false
if you don't want to extend the environment variables when providing the env
property.
Type: string
Explicitly set the value of argv[0]
sent to the child process. This will be set to command
or file
if not specified.
Type: Array
string
Default: pipe
Child's stdio configuration.
Type: boolean
Prepare child to run independently of its parent process. Specific behavior depends on the platform.
Type: number
Sets the user identity of the process.
Type: number
Sets the group identity of the process.
Type: boolean
string
Default: false
If true
, runs command
inside of a shell. Uses /bin/sh
on UNIX and cmd.exe
on Windows. A different shell can be specified as a string. The shell should understand the -c
switch on UNIX or /d /s /c
on Windows.
Type: boolean
Default: true
Strip EOF (last newline) from the output.
Type: boolean
Default: true
Prefer locally installed binaries when looking for a binary to execute.
If you $ npm install foo
, you can then execa('foo')
.
Type: string
Default: process.cwd()
Preferred path to find locally installed binaries in (use with preferLocal
).
Type: string
Buffer
stream.Readable
Write some input to the stdin
of your binary.
Streams are not allowed when using the synchronous methods.
Type: boolean
Default: true
Setting this to false
resolves the promise with the error instead of rejecting it.
Type: boolean
Default: true
Keep track of the spawned process and kill
it when the parent process exits.
Type: string
Default: utf8
Specify the character encoding used to decode the stdout
and stderr
output.
Type: number
Default: 0
If timeout is greater than 0
, the parent will send the signal identified by the killSignal
property (the default is SIGTERM
) if the child runs longer than timeout milliseconds.
Type: number
Default: 10000000
(10MB)
Largest amount of data in bytes allowed on stdout
or stderr
.
Type: string
number
Default: SIGTERM
Signal value to be used when the spawned process will be killed.
Type: string
number
Stream
undefined
null
Default: pipe
Same options as stdio
.
Type: string
number
Stream
undefined
null
Default: pipe
Same options as stdio
.
Type: string
number
Stream
undefined
null
Default: pipe
Same options as stdio
.
Type: boolean
Default: false
If true
, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to true
automatically when the shell
option is true
.
Let's say you want to show the output of a child process in real-time while also saving it to a variable.
const execa = require('execa');
const getStream = require('get-stream');
const stream = execa('echo', ['foo']).stdout;
stream.pipe(process.stdout);
getStream(stream).then(value => {
console.log('child output:', value);
});
MIT © Sindre Sorhus
FAQs
Process execution for humans
The npm package execa receives a total of 77,532,296 weekly downloads. As such, execa popularity was classified as popular.
We found that execa demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
vlt introduced its new package manager and a serverless registry this week, innovating in a space where npm has stagnated.
Security News
Research
The Socket Research Team uncovered a malicious Python package typosquatting the popular 'fabric' SSH library, silently exfiltrating AWS credentials from unsuspecting developers.
Security News
At its inaugural meeting, the JSR Working Group outlined plans for an open governance model and a roadmap to enhance JavaScript package management.